const ffi = require('ffi-napi');
const ref = require('ref-napi');
const iconvLite = require('iconv-lite');
const stringPtr = ref.refType(ref.types.CString);
let handle;

let myUser32 = new ffi.Library('user32', {
	'EnumWindows': ["bool", ["pointer", "int32"]],
	'IsWindowVisible': ["bool", ["int32"]],
	'GetWindowTextLengthW': ["int32", ["int32"]],
	'GetWindowTextA' : ['long', ['long', stringPtr, 'long']],
	'ShowWindow' : ["bool", ["int32", "int32"]],
	'CloseWindow': ["bool", ["int32"]],
});

class winffi {
	
	constructor(browserType) {
	    this.init(browserType);
	}

	init(browserType) {
		myUser32.EnumWindows(
			ffi.Callback("bool", ["int32", "int32"], (tophandle, topparamhandle) => {
				var num = myUser32.GetWindowTextLengthW(tophandle);
				if(num > 0){
					var buf, name, ret;
					buf = new Buffer.alloc(255);
					ret = myUser32.GetWindowTextA(tophandle, buf, 255);
                    // 这里不需要进行readCString转码，参考https://www.gowhich.com/blog/671
                    // buf = ref.readCString(buf, 0);
					var title = iconvLite.decode(buf, 'gbk');
					var exp = this.browserCompatible(browserType);
					var str = "百度一下，你就知道";
					if((!exp || (exp && title.indexOf(exp) != -1)) && title.indexOf(str) != -1){
						handle = tophandle;
						return false;
					}
				}
			}),
			0
		);
	}
	
	getWindowStatus(){
		var status = myUser32.IsWindowVisible(handle);
		if(status){
			this.hideWindow();
		}else{
			this.openWindow();
		}
	}

    /**
     * 显示被隐藏窗口
     */
	openWindow(){
		var openMsg = myUser32.ShowWindow(handle, 9);
		console.log('open result:' + openMsg);
		return openMsg;
	}

    /**
     * 最小化被显示窗口
     */
	hideWindow(){
		//var closeMsg = myUser32.ShowWindow(handle, 0);       //调用getWindowStatus方法时使用该方法隐藏窗口
		var isClose = myUser32.CloseWindow(handle);
		console.log('close result:' + isClose);
		return isClose;
	}
	
    /**
     * 获取不同浏览器标题后缀
     */
    browserCompatible (name) {
		var exp;
		switch(name){
			case 'Firefox':
				exp = "Mozilla Firefox";
				break;
				
			case 'Chrome':
				exp = "Google Chrome";
				break;
				
			case 'IE':
				exp = "Internet Explorer";
				break;
				
			case 'Edge':
				exp = "Microsoft Edge";
				break;
				
			default:
				exp = '';
				break;
		}
		return exp;
    }

}

module.exports = new winffi('Chrome');
